import httpx
from pydantic import BaseModel
from starlette.responses import JSONResponse
from fastapi import FastAPI, Request, HTTPException
from .api_model.response_model import ApiResponse


class AgentInput(BaseModel):
    question: str


async def ai_agent_api(request: Request, user_input: AgentInput, url):
    # 使用 httpx 发送请求到另一个服务器的 /ask-agent/ 接口
    async with httpx.AsyncClient(timeout=180.0) as client:
        try:
            response = await client.post(url, json=user_input.dict())
            # 检查响应状态码

            if response.status_code == 200:
                return ApiResponse(code=200,
                                   data=response.json(),
                                   msg="成功")
            else:
                return ApiResponse(code=200,
                                   data={
                                       "question": user_input.question,
                                       "ans": "",
                                       "type": "error",
                                       "msg": "代理请求失败"
                                   },
                                   msg="成功")
        except httpx.RequestError as e:
            # 处理请求错误
            return ApiResponse(code=200,
                               data={
                                   "question": user_input.question,
                                   "ans": "",
                                   "type": "error",
                                   "msg": "f代理请求错误: {e}"
                               },
                               msg="成功")
